package com.syys.privacy.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.syys.common.config.WeCatConfig;
import com.syys.common.utils.DateUtils;
import com.syys.common.utils.StringUtils;
import com.syys.privacy.conentDB.ParagraphDB;
import com.syys.privacy.domain.*;
import com.syys.privacy.service.*;
import com.syys.privacy.util.PrivacyWordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.syys.privacy.mapper.QaPrivacyMapper;
import com.syys.common.core.text.Convert;
import org.springframework.util.ResourceUtils;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 隐私政策Service业务层处理
 *
 * @author ys
 * @date 2021-07-13
 */
@Service
public class QaPrivacyServiceImpl implements IQaPrivacyService {

    @Autowired
    private QaPrivacyMapper qaPrivacyMapper;
    @Autowired
    private IPrivacyInfoUseService iPrivacyInfoUseService;
    @Autowired
    private IQaPersonalInfoService iQaPersonalInfoService;
    @Autowired
    private IQaPersonalInfoCommissionService iQaPersonalInfoCommissionService;
    @Autowired
    private IQaPersonalInfoSafetyService iQaPersonalInfoSafetyService;
    @Autowired
    private IQaPersonalInfoMinorService iQaPersonalInfoMinorService;
    @Autowired
    private IQaAnswerService iQaAnswerService;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 查询隐私政策
     *
     * @param id 隐私政策ID
     * @return 隐私政策
     */
    @Override
    public QaPrivacy selectQaPrivacyById(Long id) {
        return qaPrivacyMapper.selectQaPrivacyById(id);
    }

    /**
     * 查询隐私政策列表
     *
     * @param qaPrivacy 隐私政策
     * @return 隐私政策
     */
    @Override
    public List<QaPrivacy> selectQaPrivacyList(QaPrivacy qaPrivacy) {
        return qaPrivacyMapper.selectQaPrivacyList(qaPrivacy);
    }

    /**
     * 新增隐私政策
     *
     * @param qaPrivacy 隐私政策
     * @return 结果
     */
    @Override
    public int insertQaPrivacy(QaPrivacy qaPrivacy) {
        qaPrivacy.setCreateTime(DateUtils.getNowDate());
        return qaPrivacyMapper.insertQaPrivacy(qaPrivacy);
    }

    /**
     * 修改隐私政策
     *
     * @param qaPrivacy 隐私政策
     * @return 结果
     */
    @Override
    public int updateQaPrivacy(QaPrivacy qaPrivacy) {
        Integer sendFlag = qaPrivacy.getSendFlag();
        try {
            qaPrivacy.setUpdateTime(DateUtils.getNowDate());
            qaPrivacyMapper.updateQaPrivacy(qaPrivacy);
            if (sendFlag == 1) {
                qaPrivacy = this.selectQaPrivacyById(qaPrivacy.getPrivacyId());
                PrivacyInfoUse privacyInfoUse = new PrivacyInfoUse();
                privacyInfoUse.setPrivacyId(qaPrivacy.getPrivacyId());
                List<PrivacyInfoUse> privacyInfoUses = iPrivacyInfoUseService.selectPrivacyInfoUseList(privacyInfoUse);
                if (privacyInfoUses == null || privacyInfoUses.size() == 0) {
                    return 0;
                }
                privacyInfoUse = privacyInfoUses.get(0);
                PrivacyWordUtil.setiQaAnswerService(iQaAnswerService);
                Optional<Document> chapterTwo = PrivacyWordUtil.autoGenerate(privacyInfoUse, PrivacyInfoUse.class, "chapterTwo", ParagraphDB.paragraphDescChapterTwoList);

                QaPersonalInfo qaPersonalInfo = new QaPersonalInfo();
                qaPersonalInfo.setPrivacyId(qaPrivacy.getPrivacyId());
                List<QaPersonalInfo> qaPersonalInfos = iQaPersonalInfoService.selectQaPersonalInfoList(qaPersonalInfo);
                if (qaPersonalInfos == null || qaPersonalInfos.size() == 0) {
                    return 0;
                }
                qaPersonalInfo = qaPersonalInfos.get(0);
                Optional<Document> chapterThree = PrivacyWordUtil.autoGenerate(qaPersonalInfo, QaPersonalInfo.class, "chapterThree", ParagraphDB.paragraphDescChapterThreeList);

                Optional<Document> chapterFour = PrivacyWordUtil.autoGenerate(null, null, "chapterFour", ParagraphDB.paragraphDescChapterFourList);

                QaPersonalInfoCommission qaPersonalInfoCommission = new QaPersonalInfoCommission();
                qaPersonalInfoCommission.setPrivacyId(qaPrivacy.getPrivacyId());
                List<QaPersonalInfoCommission> qaPersonalInfoCommissions = iQaPersonalInfoCommissionService.selectQaPersonalInfoCommissionList(qaPersonalInfoCommission);
                if (qaPersonalInfoCommissions == null || qaPersonalInfoCommissions.size() == 0) {
                    return 0;
                }
                qaPersonalInfoCommission = qaPersonalInfoCommissions.get(0);
                Optional<Document> chapterFives = PrivacyWordUtil.autoGenerate(qaPersonalInfoCommission, QaPersonalInfoCommission.class, "chapterFives", ParagraphDB.paragraphDescChapterFivesList);

                Optional<Document> chapterSix = PrivacyWordUtil.autoGenerate(null, null, "chapterSix", ParagraphDB.paragraphDescChapterSixList);

                QaPersonalInfoSafety qaPersonalInfoSafety = new QaPersonalInfoSafety();
                qaPersonalInfoSafety.setPrivacyId(qaPrivacy.getPrivacyId());
                List<QaPersonalInfoSafety> qaPersonalInfoSafeties = iQaPersonalInfoSafetyService.selectQaPersonalInfoSafetyList(qaPersonalInfoSafety);
                if (qaPersonalInfoSafeties == null || qaPersonalInfoSafeties.size() == 0) {
                    return 0;
                }
                qaPersonalInfoSafety = qaPersonalInfoSafeties.get(0);
                Optional<Document> chapterSeven = PrivacyWordUtil.autoGenerate(qaPersonalInfoSafety, QaPersonalInfoSafety.class, "chapterSeven", ParagraphDB.paragraphDescChapterSevenList);

                Optional<Document> chapterEight = PrivacyWordUtil.autoGenerate(null, null, "chapterEight", ParagraphDB.paragraphDescChapterEightList);

                QaPersonalInfoMinor qaPersonalInfoMinor = new QaPersonalInfoMinor();
                qaPersonalInfoMinor.setPrivacyId(qaPrivacy.getPrivacyId());
                List<QaPersonalInfoMinor> qaPersonalInfoMinors = iQaPersonalInfoMinorService.selectQaPersonalInfoMinorList(qaPersonalInfoMinor);
                if (qaPersonalInfoMinors == null || qaPersonalInfoMinors.size() == 0) {
                    return 0;
                }
                qaPersonalInfoMinor = qaPersonalInfoMinors.get(0);
                Optional<Document> chapterNine = PrivacyWordUtil.autoGenerate(qaPersonalInfoMinor, QaPersonalInfoMinor.class, "chapterNine", ParagraphDB.paragraphDescChapterNineList);

                Optional<Document> chapterTen = PrivacyWordUtil.autoGenerate(null, null, "chapterTen", ParagraphDB.paragraphDescChapterTenList);

                Optional<Document> chapterEleven = PrivacyWordUtil.autoGenerate(null, null, "chapterEleven", ParagraphDB.paragraphDescChapterElevenList);

                File path = new File(ResourceUtils.getURL("classpath:PrivacyPolicyTemplate.docx").getPath());
                Document document = new Document(path.getPath());

                PrivacyWordUtil.copyDocument(document, chapterTwo);
                PrivacyWordUtil.copyDocument(document, chapterThree);
                PrivacyWordUtil.copyDocument(document, chapterFour);
                PrivacyWordUtil.copyDocument(document, chapterFives);
                PrivacyWordUtil.copyDocument(document, chapterSix);
                PrivacyWordUtil.copyDocument(document, chapterSeven);
                PrivacyWordUtil.copyDocument(document, chapterEight);
                PrivacyWordUtil.copyDocument(document, chapterNine);
                PrivacyWordUtil.copyDocument(document, chapterTen);
                PrivacyWordUtil.copyDocument(document, chapterEleven);

                //使用新文本替换文档中的指定文本
                document.replace("【产品名称】", StringUtils.defaultIfEmpty(qaPrivacy.getBrandName(), ""), false, true);
                document.replace("【公司名称】", StringUtils.defaultIfEmpty(qaPrivacy.getCompanyName(), ""), false, true);
                document.replace("【联系电话】", StringUtils.defaultIfEmpty(qaPrivacy.getPhone(), ""), false, true);
                document.replace("【电子邮件】", StringUtils.defaultIfEmpty(qaPrivacy.getEmail(), ""), false, true);
                document.replace("【联系地址】", StringUtils.defaultIfEmpty(qaPrivacy.getContactAddress(), ""), false, true);
                document.replace("【客服热线】", StringUtils.defaultIfEmpty(qaPrivacy.getCustomerServiceHotline(), ""), false, true);
                document.replace("【邮寄地址】", StringUtils.defaultIfEmpty(qaPrivacy.getMailingAddress(), ""), false, true);
                document.replace("【收件人】", StringUtils.defaultIfEmpty(qaPrivacy.getRecipient(), ""), false, true);
                document.replace("【更新日期】", DateUtils.dateTimeNow("yyyy年MM月dd日"), false, true);
                String saveFilePath = WeCatConfig.getDownloadPath() + "/" + qaPrivacy.getPrivacyId() + "/" + qaPrivacy.getCompanyName() + "隐私政策.docx";
                File file = new File(saveFilePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                document.saveToFile(saveFilePath, FileFormat.Docx_2013);
                document.dispose();

                QaPrivacy finalQaPrivacy = qaPrivacy;

                new Thread(() -> {
                    sendMail(finalQaPrivacy, saveFilePath);
                }).start();
                PrivacyWordUtil.serialNumLocal.set(null);
            }
        } catch (IllegalAccessException | FileNotFoundException e) {
            new RuntimeException("文档生成失败！");
        }
        return 1;
    }

    private void sendMail(QaPrivacy qaPrivacy, String saveFilePath) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom("cyberdatalaw@163.com");
            helper.setTo(qaPrivacy.getSendMail());
            helper.setSubject(qaPrivacy.getBrandName() + "隐私政策——自动生成文本");
            String content = "<html>\n" +
                    "<body>\n" +
                    "<p>尊敬的用户您好:</p>\n" +
                    "<p style='text-indent: 2em;'>根据您的问卷填写情况为您生成的隐私政策文本详见附件。</p>\n" +
                    "<p style='text-indent: 2em;'><strong>需要特别提醒您注意的是：</strong>本工具所生成的文本仅供参考，不代表任何正式的法律意见或合规建议，如您需要正式的法律意见或合规建议，请向专业的律师或其他合规专业人士咨询。</p>\n" +
                    "<p style='text-indent: 2em;'>如您有任何意见、建议或进一步的合规需求，可直接通过本邮箱与我们联系。</p>\n" +
                    "<p style='text-indent: 2em;'>感谢您的使用，祝您生活愉快！</p>\n\n" +
                    "<p>————</p>\n" +
                    "<p>网络与数据法律观察（CyberDataLaw.cn）</p>\n" +
                    "</body>\n" +
                    "</html>";

            helper.setText(content, true);
            FileSystemResource file1 = new FileSystemResource(new File(saveFilePath));
            String brandName = qaPrivacy.getBrandName().replaceAll(" ", "");
            if (StringUtils.isEmpty(brandName)) {
                brandName = UUID.randomUUID().toString();
            }
            helper.setEncodeFilenames(false);
            helper.addAttachment(brandName + "隐私政策.docx", file1);
            this.mailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new RuntimeException("发送邮件错误！", e);
        }
    }

    /**
     * 删除隐私政策对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteQaPrivacyByIds(String ids) {
        return qaPrivacyMapper.deleteQaPrivacyByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除隐私政策信息
     *
     * @param id 隐私政策ID
     * @return 结果
     */
    @Override
    public int deleteQaPrivacyById(Long id) {
        return qaPrivacyMapper.deleteQaPrivacyById(id);
    }

    @Override
    public Long saveQaPrivacy(QaPrivacy qaPrivacy) {
        if (StringUtils.isNull(qaPrivacy.getPrivacyId())) {
            qaPrivacy.setCreateTime(DateUtils.getNowDate());
            qaPrivacyMapper.insertQaPrivacy(qaPrivacy);
        } else {
            qaPrivacy.setUpdateTime(DateUtils.getNowDate());
            qaPrivacyMapper.updateQaPrivacy(qaPrivacy);
        }
        return qaPrivacy.getPrivacyId();
    }
}
